/**
 * 终极透明材质修复工具
 * 彻底解决黑色透明区域问题
 */

class UltimateTransparencyFixer {
    constructor() {
        this.fixedMaterials = new Set();
        this.debugMode = true;
    }

    /**
     * 立即修复所有透明材质问题
     */
    fixAll() {
        console.log('\n🚀 启动终极透明材质修复...\n');
        
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }

        let fixedCount = 0;
        let totalMaterials = 0;

        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                materials.forEach((material, index) => {
                    totalMaterials++;
                    const matName = material.userData?.materialName || material.name || `未命名_${totalMaterials}`;
                    
                    // 检查是否需要修复
                    if (this.needsFix(material, matName)) {
                        console.log(`\n🔧 修复材质: ${matName}`);
                        console.log(`   Mesh: ${obj.name}`);
                        console.log(`   修复前: transparent=${material.transparent}, alphaTest=${material.alphaTest}, opacity=${material.opacity}`);
                        console.log(`   修复前颜色: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
                        
                        if (this.applyUltimateFix(material, matName, obj)) {
                            fixedCount++;
                        }
                    }
                });
            }
        });

        console.log(`\n✅ 修复完成！处理了 ${fixedCount}/${totalMaterials} 个材质`);
        
        // 强制渲染更新
        if (window.manager && window.manager.render) {
            window.manager.render();
        }
        
        return fixedCount;
    }

    /**
     * 检查材质是否需要修复
     */
    needsFix(material, matName) {
        // 跳过已修复的材质
        if (this.fixedMaterials.has(material.uuid)) {
            return false;
        }

        // 检查是否为透明材质
        const isTransparent = material.transparent || material.alphaTest > 0 || material.opacity < 1;
        
        // 检查是否有贴图
        const hasTexture = material.map !== null;
        
        // 检查是否为马路线等需要特殊处理的材质
        const isSpecialMaterial = matName.toLowerCase().includes('马路') || 
                                matName.toLowerCase().includes('线') ||
                                matName.toLowerCase().includes('road') ||
                                matName.toLowerCase().includes('line');

        return isTransparent || hasTexture || isSpecialMaterial;
    }

    /**
     * 应用终极修复
     */
    applyUltimateFix(material, matName, mesh) {
        const isRoadLine = matName.toLowerCase().includes('马路') || 
                          matName.toLowerCase().includes('线') ||
                          matName.toLowerCase().includes('road') ||
                          matName.toLowerCase().includes('line');

        let fixed = false;

        // 🎯 策略1: 马路线材质专用修复
        if (isRoadLine) {
            console.log(`   🛣️ 应用马路线专用修复`);
            
            // 强制使用alphaTest模式
            material.transparent = false;
            material.alphaTest = 0.01; // 极低阈值，几乎显示所有像素
            material.depthWrite = true;
            material.depthTest = true;
            material.side = 2; // DoubleSide，确保双面显示
            
            // 设置渲染顺序
            mesh.renderOrder = 100;
            
            // 如果有贴图，分析贴图内容
            if (material.map && material.map.image && material.map.image.complete) {
                const analysis = this.analyzeTexture(material.map);
                console.log(`   📊 贴图分析: ${analysis.summary}`);
                
                if (analysis.isDark) {
                    console.log(`   🚨 检测到暗色贴图，应用颜色补偿`);
                    // 对于暗色贴图，适度提升基础颜色
                    const boost = Math.min(3.0, 1.0 / Math.max(analysis.avgBrightness, 0.1));
                    material.color.multiplyScalar(boost);
                    console.log(`   🔧 颜色补偿系数: ${boost.toFixed(2)}`);
                }
            }
            
            fixed = true;
        }
        
        // 🎯 策略2: 其他透明材质修复
        else if (material.transparent || material.alphaTest > 0 || material.opacity < 1) {
            console.log(`   🌿 应用通用透明材质修复`);
            
            if (material.map) {
                // 有贴图的透明材质
                if (material.alphaTest > 0) {
                    // 使用alphaTest模式
                    material.transparent = false;
                    material.alphaTest = Math.max(0.1, material.alphaTest);
                    material.depthWrite = true;
                } else {
                    // 使用transparent模式
                    material.transparent = true;
                    material.depthWrite = false;
                }
            } else {
                // 无贴图的透明材质，检查是否过暗
                const brightness = (material.color.r + material.color.g + material.color.b) / 3;
                if (brightness < 0.5) {
                    console.log(`   🔧 提升暗色材质亮度: ${brightness.toFixed(3)} → ${Math.min(0.8, brightness * 2).toFixed(3)}`);
                    material.color.multiplyScalar(Math.min(2.0, 0.8 / brightness));
                }
            }
            
            fixed = true;
        }
        
        // 🎯 策略3: 强制修复所有有贴图的材质
        else if (material.map) {
            console.log(`   🖼️ 应用有贴图材质修复`);
            
            // 确保有贴图的材质有合理的透明设置
            if (!material.transparent && material.alphaTest === 0) {
                // 如果没有透明设置，检查贴图是否有透明通道
                if (material.map.format === 1023) { // RGBA format
                    material.alphaTest = 0.1;
                    console.log(`   🔧 检测到RGBA贴图，启用alphaTest`);
                }
            }
            
            fixed = true;
        }

        if (fixed) {
            material.needsUpdate = true;
            this.fixedMaterials.add(material.uuid);
            
            console.log(`   修复后: transparent=${material.transparent}, alphaTest=${material.alphaTest}, opacity=${material.opacity}`);
            console.log(`   修复后颜色: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
            console.log(`   渲染顺序: ${mesh.renderOrder}`);
        }

        return fixed;
    }

    /**
     * 分析贴图内容
     */
    analyzeTexture(texture) {
        try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = texture.image;
            
            canvas.width = Math.min(img.width, 50);
            canvas.height = Math.min(img.height, 50);
            
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const data = imageData.data;
            
            let totalR = 0, totalG = 0, totalB = 0, totalA = 0;
            let opaquePixels = 0;
            let transparentPixels = 0;
            const pixelCount = data.length / 4;
            
            for (let i = 0; i < data.length; i += 4) {
                const r = data[i];
                const g = data[i + 1];
                const b = data[i + 2];
                const a = data[i + 3];
                
                totalA += a;
                
                if (a > 128) {
                    totalR += r;
                    totalG += g;
                    totalB += b;
                    opaquePixels++;
                } else {
                    transparentPixels++;
                }
            }
            
            const avgAlpha = totalA / pixelCount;
            const avgBrightness = opaquePixels > 0 ? (totalR + totalG + totalB) / (opaquePixels * 3 * 255) : 0;
            const isDark = avgBrightness < 0.2;
            
            return {
                avgBrightness,
                avgAlpha,
                opaquePixels,
                transparentPixels,
                isDark,
                summary: `亮度=${(avgBrightness*100).toFixed(1)}%, Alpha=${avgAlpha.toFixed(0)}, 不透明=${opaquePixels}, 透明=${transparentPixels}`
            };
        } catch (error) {
            return {
                avgBrightness: 0.5,
                avgAlpha: 255,
                opaquePixels: 0,
                transparentPixels: 0,
                isDark: false,
                summary: `分析失败: ${error.message}`
            };
        }
    }

    /**
     * 专门修复马路线材质
     */
    fixRoadLines() {
        console.log('\n🛣️ 专门修复马路线材质...\n');
        
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }

        let fixedCount = 0;

        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                materials.forEach((material) => {
                    const matName = material.userData?.materialName || material.name || '';
                    const meshName = obj.name || '';
                    
                    if (matName.includes('马路线') || matName.includes('马路') || 
                        meshName.includes('马路线') || meshName.includes('马路')) {
                        
                        console.log(`🔧 强力修复马路线: ${matName || meshName}`);
                        console.log(`   修复前: transparent=${material.transparent}, alphaTest=${material.alphaTest}`);
                        console.log(`   修复前颜色: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
                        
                        // 超强修复
                        material.transparent = false;
                        material.alphaTest = 0.001; // 极极低阈值
                        material.depthWrite = true;
                        material.depthTest = true;
                        material.side = 2; // 双面显示
                        
                        // 颜色补偿
                        if (material.color.r < 0.8 && material.color.g < 0.8 && material.color.b < 0.8) {
                            material.color.setRGB(
                                Math.min(2.0, material.color.r * 3),
                                Math.min(2.0, material.color.g * 3),
                                Math.min(2.0, material.color.b * 3)
                            );
                        }
                        
                        // 设置高优先级渲染顺序
                        obj.renderOrder = 50;
                        
                        material.needsUpdate = true;
                        fixedCount++;
                        
                        console.log(`   修复后: transparent=${material.transparent}, alphaTest=${material.alphaTest}`);
                        console.log(`   修复后颜色: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
                        console.log(`   渲染顺序: ${obj.renderOrder}`);
                    }
                });
            }
        });

        console.log(`\n✅ 马路线修复完成！修复了 ${fixedCount} 个材质`);
        
        // 强制渲染
        if (window.manager && window.manager.render) {
            window.manager.render();
        }
        
        return fixedCount;
    }

    /**
     * 清除修复记录，重新修复
     */
    reset() {
        this.fixedMaterials.clear();
        console.log('🔄 已清除修复记录');
    }
}

// 创建全局实例
window.ultimateFixer = new UltimateTransparencyFixer();

// 导出便捷方法
window.fixTransparency = () => window.ultimateFixer.fixAll();
window.fixRoadLines = () => window.ultimateFixer.fixRoadLines();
window.resetFixer = () => window.ultimateFixer.reset();

console.log('🚀 终极透明材质修复工具已加载！');
console.log('使用方法:');
console.log('  fixTransparency() - 修复所有透明材质');
console.log('  fixRoadLines() - 专门修复马路线');
console.log('  resetFixer() - 重置修复记录');
